const { Controller } = require("egg");

class UserController extends Controller {
    /**
     * 修改用户密码
     */
    async changePassword() {
        // 获取请求体参数
        const { oldPassword, newPassword } = this.ctx.request.body;
        // 从身份认证中间件中，去解析 token 后的用户信息
        const uid = this.ctx.user.id;
        // 查询数据库用户，并修改
        const user = await this.service.user.findByUsername(
            this.ctx.user.username
        );
        // 新密码不能和旧密码相等
        if (user.password === this.ctx.helper.passwordEncoder(newPassword)) {
            this.ctx.body = {
                code: 400,
                message: "新密码不能和旧密码相等",
            };
            return;
        }
        // 判断旧密码是否相等
        if (user.password !== this.ctx.helper.passwordEncoder(oldPassword)) {
            this.ctx.body = {
                code: 400,
                message: "旧密码错误",
            };
            return;
        }
        // 修改密码
        const res = await this.service.user.updatePassword(
            this.ctx.helper.passwordEncoder(newPassword),
            uid
        );
        // 判断是否修改成功
        if (res.affectedRows !== 1) {
            this.ctx.body = {
                code: 500,
                message: "密码修改失败",
            };
            return;
        }
        this.ctx.body = {
            code: 200,
            message: "密码修改成功",
        };
    }

    /**
     * 注销用户
     */
    async remove() {
        const res = await this.service.user.remove(this.ctx.user.id);
        if (res.affectedRows !== 1) {
            this.ctx.body = {
                code: 500,
                message: "注销失败",
            };
        } else {
            this.ctx.body = {
                code: 204,
                message: "用户注销成功",
            };
        }
    }

    /**
     * 修改用户信息
     */
    async update() {
        // 获取请求参数
        const { nickname } = this.ctx.request.body;
        const res = await this.service.user.update(nickname);
        if (res.affectedRows !== 1) {
            this.ctx.body = {
                code: 500,
                message: "修改用户信息失败",
            };
        } else {
            this.ctx.body = {
                code: 200,
                message: "修改成功",
            };
        }
    }
}

module.exports = UserController;
